from django.contrib import admin
from goods import models


# 在 admin.py 文件中, 定义一个 admin 管理类, 继承自 admin.ModelAdmin
class SKUAdmin(admin.ModelAdmin):
    # 在管理类中, 重写 save_model 函数
    def save_model(self, request, obj, form, change):
        # 将用户在 admin站点 的操作保存.
        obj.save()

        # 调用我们的 celery 代码, 触发异步任务
        # 导入 html 任务中的函数
        from celery_tasks.html.tasks import generate_static_sku_detail_html
        # 将函数加入到中间人队列中, 进行执行.
        generate_static_sku_detail_html.delay(obj.id)


# 下面的操作类似上面的
class SKUSpecificationAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.save()
        from celery_tasks.html.tasks import generate_static_sku_detail_html
        generate_static_sku_detail_html.delay(obj.sku.id)

    def delete_model(self, request, obj):
        sku_id = obj.sku.id
        obj.delete()
        from celery_tasks.html.tasks import generate_static_sku_detail_html
        generate_static_sku_detail_html.delay(sku_id)


class SKUImageAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.save()
        from celery_tasks.html.tasks import generate_static_sku_detail_html
        generate_static_sku_detail_html.delay(obj.sku.id)

        # 设置SKU默认图片
        sku = obj.sku
        if not sku.default_image_url:
            sku.default_image_url = obj.image.url
            sku.save()

    def delete_model(self, request, obj):
        sku_id = obj.sku.id
        obj.delete()
        from celery_tasks.html.tasks import generate_static_sku_detail_html
        generate_static_sku_detail_html.delay(sku_id)


admin.site.register(models.GoodsCategory)
admin.site.register(models.GoodsChannel)
admin.site.register(models.Goods)
admin.site.register(models.Brand)
admin.site.register(models.GoodsSpecification)
admin.site.register(models.SpecificationOption)
admin.site.register(models.SKU, SKUAdmin)
admin.site.register(models.SKUSpecification, SKUSpecificationAdmin)
admin.site.register(models.SKUImage, SKUImageAdmin)
